const gulp = require('gulp');
const gulpClean = require('gulp-clean'); // 清除文件
const sass = require('gulp-sass'); // 编译scss
const concat = require('gulp-concat'); // 合并css
const cleanCss = require('gulp-clean-css'); // css压缩
const autoprefixer = require('gulp-autoprefixer'); // css加前缀
const babel = require("gulp-babel"); // 编译js，兼容当前浏览器
const jshint = require("gulp-jshint");// js检查
const uglify = require('gulp-uglify'); // js压缩
const rename = require('gulp-rename'); // 文件重命名
const { outPutPath } = require('./config') // 站点配置信息

// 清除dist文件
function clean() {
  return gulp.src([`${outPutPath}*`], { read: false })
    .pipe(gulpClean());
}

// 组件css：处理css、scss，压缩、加前缀合并
function handleComponentsCss() {
  return gulp.src(['views/components/**/*.{css,scss}'])
    .pipe(sass())//编译scss
    .pipe(concat('components/components.min.css'))
    .pipe(autoprefixer({
      overrideBrowserslist: ['last 2 versions'],
      cascade: false
    }))
    .pipe(cleanCss())
    .pipe(gulp.dest(outPutPath))
}

// 所有css：处理css、scss，压缩、加前缀，单独存放
function handleCss() {
  return gulp.src(['views/**/*.{css,scss}'])
    .pipe(sass())//编译scss
    .pipe(autoprefixer({
      overrideBrowserslist: ['last 2 versions'],
      cascade: false
    }))
    .pipe(cleanCss())
    .pipe(rename(function (path) {
      // console.log('path',path)
    }))
    .pipe(gulp.dest(outPutPath))
}

// 组件js： 合并js，检查js、编译js、压缩js
function handleComponentsJs() {
  return gulp.src(['views/components/**/*.js'])
    .pipe(concat('components/components.min.js')) // 多个js合并成一个
    .pipe(jshint())//检查代码
    .pipe(babel({//编译ES6
      presets: ['es2015']
    }))
    .pipe(uglify())//压缩js
    .pipe(gulp.dest(outPutPath))
}

// 所有js：检查js、编译js、压缩js，单独存放
function handleJs() {
  return gulp.src(['views/**/*.js'])
    .pipe(jshint())//检查代码
    .pipe(babel({//编译ES6
      presets: ['es2015']
    }))
    .pipe(uglify())//压缩js
    .pipe(gulp.dest(outPutPath))
}

// 所有图片复制到打包目录
function handleImg() {
  return gulp.src(['views/**/*.{png,jpg,gif,ico,jpeg}'])
    .pipe(gulp.dest(outPutPath));
}

// 监听所有文件
function watch() {
  gulp.watch(['views/**/*.*'], function () {
    console.log('文件改变')
    debounceBuild()
  });
}

// 防抖
function debounce(fn, delay) {
  var timer = null;
  return function () {
    var that = this;
    var args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(that, args)
    }, delay)
  }
}

// 打包防抖
var debounceBuild = debounce(function () {
  start()
}, 3000)

const build = gulp.series(clean, handleComponentsCss, handleCss, handleComponentsJs, handleJs, handleImg);
const start = gulp.series(build, watch);

// 打包
exports.build = build;
// 打包、监听文件改变自动打包
exports.watch = start;